//
//  KSOSHomeController.m
//  Keping
//
//  Created by a on 2017/9/16.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KSOSHomeController.h"
#import "KSOSContactListController.h"
#import "GPSOSContactListController.h"
#import "KSOSRequest.h"
#import "GPLocationManager.h"
#import "GPChatViewModel.h"
#import "KSosListModel.h"

#import "KTitleBtnView.h"

@interface KSOSHomeController () <UIImagePickerControllerDelegate>
/**
 背景图片
 */
@property(nonatomic,weak)UIImageView*bgImgView;
/**
 求助按钮
 */
@property(nonatomic,weak)UIButton*SeekHelpBtn;
/**开关*/
@property(nonatomic,weak) UISwitch *swButton;

/**是否添加过紧急求助联系人*/
@property(nonatomic,assign) BOOL isHasContact;

@end

@implementation KSOSHomeController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[GPLocationManager shareManager] requestCurrentLocationOnce:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //self.navBarBgAlpha = @"1.0";
//    self.swButton.on = NO;  //页面离开时自动选择关闭
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    //获取GPS的状态
    WEAKSELF
    [self getSosStatus:^(BOOL success, BOOL status) {
        if (success) {
            weakSelf.swButton.on = status;
        }else{
            weakSelf.swButton.on = NO;
        }
    }];
}

-(void)setUI
{
    WEAKSELF;
    self.navigationItem.title=@"SOS";
    self.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImage:@"cctv_enum" withName:nil target:self action:@selector(clickRight)];
    //背景图片
    UIImageView*bgImgView=[[UIImageView alloc]init];
    [self.view addSubview:bgImgView];
    self.bgImgView=bgImgView;
    bgImgView.image=[UIImage imageNamed:@"sos_warning_bg"];
    [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view).offset(-64);
    }];
    
    //求助按钮
    CGFloat seekWH=K_FactorW(200);
    UIButton*SeekHelpBtn=[[UIButton alloc]init];
    [SeekHelpBtn addTarget:self action:@selector(uploadLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:SeekHelpBtn];
    self.SeekHelpBtn=SeekHelpBtn;
    [SeekHelpBtn setImage:[UIImage imageNamed:@"sos_warning"] forState:UIControlStateNormal];
    [SeekHelpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(seekWH, seekWH));
        make.centerX.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view.mas_centerY);
    }];
    
    //提示
    UILabel*explainLabel=[[UILabel alloc]init];
    [self.view addSubview:explainLabel];
    explainLabel.text=@"Always Enable GPS";
    explainLabel.textColor=[UIColor whiteColor];
    [explainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(SeekHelpBtn.mas_bottom).offset(K_FactorH(20));
        make.centerX.mas_equalTo(weakSelf.view);
    }];
    
    //开关
    UISwitch*sw=[[UISwitch alloc]init];
    [self.view addSubview:sw];
    [sw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(explainLabel.mas_right).offset(K_FactorW(20));
        make.centerY.mas_equalTo(explainLabel);
    }];
    [sw addTarget:self action:@selector(swValueChanged:) forControlEvents:UIControlEventValueChanged];
    self.swButton = sw;
    
    //照相按钮
    KTitleBtnView*photoBtn=[[KTitleBtnView alloc]init];
    photoBtn.label.text=@"Snap";
     [photoBtn.btn setImage:[UIImage imageNamed:@"sos_camera"] forState:UIControlStateNormal];
    [photoBtn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(takePhoto)]];
    [self.view addSubview:photoBtn];
    CGFloat W= K_FactorW(100);
    CGFloat H= K_FactorH(140);
    CGFloat marign=(App_Frame_Width-2*W)/2;
    [photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(weakSelf.view).offset(-K_FactorH(60));
        make.right.mas_equalTo(weakSelf.view.mas_centerX).offset(-marign/2);
        make.size.mas_equalTo(CGSizeMake(W, H));
    }];
    
    
    //test按钮
    KTitleBtnView*testBtn=[[KTitleBtnView alloc]init];
    testBtn.label.text=@"Test";
     [testBtn.btn setImage:[UIImage imageNamed:@"sos_test"] forState:UIControlStateNormal];
    [testBtn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testSOS)]];
    [self.view addSubview:testBtn];
    [testBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(photoBtn);
        make.left.mas_equalTo(weakSelf.view.mas_centerX).offset(marign/2);
        make.size.mas_equalTo(CGSizeMake(W, H));
    }];

    
}
-(void)clickRight
{
    KSOSContactListController*vc=[KSOSContactListController new];
    [self.navigationController pushViewController:vc animated:YES];
}

/**照相*/
- (void)takePhoto
{
    if(![AppGlobal isCameraDeviceAvalable]){
        return;
    }
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

/**测试SOS*/
- (void)testSOS
{
    CLLocation *location = [GPLocationManager shareManager].currentLocation;
    GPSOSContactListController * vc = [[GPSOSContactListController alloc] init];
    vc.image = nil;
    vc.isTest = YES;
    vc.latitude = location.coordinate.latitude;
    vc.longitude = location.coordinate.longitude;
    [self.navigationController pushViewController:vc animated:YES];
}

/**求救 - 上传经纬度*/
- (void)uploadLocation
{
    
    if (!self.swButton.isOn) {
        [self showText:@"Please enable GPS"];
        return;
    }
    
    [self showLoading];
    KSOSContactListController *listVc = [[KSOSContactListController alloc] init];
    [listVc loadContactList:^(BOOL success, NSArray *contacts) {
       
        WEAKSELF
        if (!success || contacts.count == 0) {
            
            [weakSelf hideHUD];
            
            UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:@"You haven't added any emergency contact." preferredStyle:UIAlertControllerStyleAlert];
            [ac addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
            [ac addAction:[UIAlertAction actionWithTitle:@"Proceed" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                //跳转到添加联系人界面
                KSOSContactListController*vc=[KSOSContactListController new];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            }]];
            
            [self presentViewController:ac animated:YES completion:nil];
            
            
            return;
        }

        
        
        //获取当前的经纬度，并上传
        if([GPLocationManager shareManager].currentLocation)
        {
            CLLocation *location = [GPLocationManager shareManager].currentLocation;
            
            KSOSRequest *request = [[KSOSRequest alloc] initWithURL:kSosUploadLocationURL];
            request.isPost = YES;
            request.params = @{@"latitude":@(location.coordinate.latitude),
                               @"longitude":@(location.coordinate.longitude)};
            [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                
                [self hideHUD];
                
                NSDictionary *response = request.responseJSONObject;
                if ([response[@"statusCode"] integerValue] != 200) {
                    
                    [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
                    return;
                }
                
                [self showSuccess:@"success"];
                
                // 给全部的紧急联系人发送SOS紧急消息
                //快速发送求救信息
                for (KSosListModel *model in contacts) {
                    
                    GPChatViewModel *chatViewModel =  [[GPChatViewModel alloc] initWithChatType:EMChatTypeChat conversationId:model.phone toId:model.phone toNickName:model.nickName toAvatarURLPath:[KGetImageURL stringByAppendingPathComponent:model.profile]];
                    
                    NSString *locationString = [NSString stringWithFormat:@"%f,%f", location.coordinate.latitude, location.coordinate.longitude];
                    
                    [chatViewModel sendSOSLocationMessage:locationString latitude:location.coordinate.latitude longitude:location.coordinate.longitude];
                    
                }
                
                
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    GPSOSContactListController * vc = [[GPSOSContactListController alloc] init];
//                    vc.image = nil;
//                    vc.isTest = NO;
//                    vc.locationString = [NSString stringWithFormat:@"%f,%f", location.coordinate.latitude, location.coordinate.longitude];
//                    [self.navigationController pushViewController:vc animated:YES];
//
//                });
                
                
            } failure:^(__kindof KBaseRequest * _Nonnull request) {
                
                [self hideHUD];
                
                [self showErrorText:@"Failture"];
                
            }];

            
            
        }else{
            [[GPLocationManager shareManager] requestCurrentLocationOnce:nil];
            [self hideHUD];
            [self showErrorText:@"Failture"];
        }
        
    }];
}


//设置SOS状态
- (void)setSosStatus:(BOOL)on completion:(void(^)(BOOL success))completion
{
    KSOSRequest *request = [[KSOSRequest alloc] initWithURL:KUpdateprofileURL];
    request.isPost = YES;
    NSString *gpsStr = on?@"Y":@"N";
    request.params = @{@"gps":gpsStr};
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        if (completion) {
            completion(YES);
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        if (completion) {
            completion(NO);
        }
    }];
}

//获取SOS状态
- (void)getSosStatus:(void(^)(BOOL success, BOOL status))completion
{
    KSOSRequest *request = [[KSOSRequest alloc] initWithURL:kSosGPSStatusURL];
    request.isPost = NO;
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
       
        NSDictionary *response = request.responseJSONObject;
        if (![response[@"statusCode"] isEqualToString:@"200"]) {
            if (completion) {
                completion(NO, NO);
            }
            return;
        }
        
        NSDictionary *partyView =  response[@"partyView"];
        BOOL status = [partyView[@"gps"] isEqualToString:@"Y"];
        if (completion) {
            completion(YES, status);
        }
       
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
        if (completion) {
            completion(NO, NO);
        }
        
    }];
}


#pragma mark - action
- (void)swValueChanged:(UISwitch *)sw
{
    BOOL on = sw.isOn;
    
    [self setSosStatus:on completion:^(BOOL success) {
        if (!success) {
            sw.on = !sw.isOn;
        }
    }];
}



#pragma mark - UIImagePickerControllerDelegate
/**拍照*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    WEAKSELF
    [self dismissViewControllerAnimated:YES completion:^{
        // 1.获取并压缩用户拍摄的图片
        UIImage *selectedImg = info[UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(selectedImg, 0.3); // 图片分辨率降低
        selectedImg = [UIImage imageWithData: imageData];
        
        // 2.跳转
        CLLocation *location = [GPLocationManager shareManager].currentLocation;
        GPSOSContactListController * vc = [[GPSOSContactListController alloc] init];
        vc.image = selectedImg;
        vc.isTest = NO;
        vc.latitude = location.coordinate.latitude;
        vc.longitude = location.coordinate.longitude;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
}

@end
